package com.lt.exam.zhuhemoshi;


import java.util.ArrayList;
import java.util.List;


public class Composite extends Component {
    List<Component> list = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }


    @Override
    public void add(Component c) {
        if(list.contains(c)){
            System.out.println("已存在，添加失败");
        }else{
            list.add(c);
        }
        return;
    }

    @Override
    public void remove(Component c) {
        if (list.contains(c)){
            list.remove(c);
        }else{
            System.out.println("不存在，删除失败");
        }
        return;
    }

    @Override
    public Component getChild(int i) {
        if (!list.isEmpty()){
            System.out.println("不存在该下级元素");
            return null;
        }
        if (i>list.size()||i<0){
            System.out.println("查询失败，请检查输入的i值");
        }else{
            return list.get(i);
        }
        System.out.println("查询失败");
        return null;
    }

    @Override
    public void print(){
        work();
        System.out.print("{");
        for (Component c: list) {
                c.print();
        }
        System.out.print("}、");
    }

    @Override
    public void work(){
        System.out.print(name);
    }
}
